import 'package:flutter/material.dart';
import 'dart:async';
import 'dart:math';

void main() {
  runApp(const MyApp());
}

class MyApp extends StatelessWidget {
  const MyApp({super.key});

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: '计算小助手',
      theme: ThemeData(
        colorScheme: ColorScheme.fromSeed(seedColor: Colors.amber),
      ),
      home: const HomePage(),
    );
  }
}

class HomePage extends StatelessWidget {
  const HomePage({super.key});

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: const Color(0xFFFFF3B0),
      appBar: AppBar(
        backgroundColor: const Color(0xFFFFE082),
        elevation: 0,
        centerTitle: true,
        title: const Text(
          '计算小助手',
          style: TextStyle(
            color: Colors.black87,
            fontSize: 22,
            fontWeight: FontWeight.bold,
          ),
        ),
      ),
      body: Column(
        children: [
          const SizedBox(height: 30),
          Padding(
            padding: const EdgeInsets.symmetric(horizontal: 20.0),
            child: GestureDetector(
              onTap: () {
                Navigator.push(
                  context,
                  MaterialPageRoute(builder: (context) => const BasicCalculationPage()),
                );
              },
              child: Card(
                color: const Color(0xFFFFE082),
                elevation: 6,
                shape: RoundedRectangleBorder(
                  borderRadius: BorderRadius.circular(16),
                ),
                child: Padding(
                  padding: const EdgeInsets.all(24.0),
                  child: Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: const [
                      Text(
                        '基本计算',
                        style: TextStyle(
                          fontSize: 28,
                          fontWeight: FontWeight.w300,
                          color: Colors.brown,
                        ),
                      ),
                      SizedBox(height: 10),
                      Text(
                        '训练最基本的加减乘除，打好数资基础',
                        style: TextStyle(
                          fontSize: 16,
                          color: Colors.brown,
                        ),
                      ),
                    ],
                  ),
                ),
              ),
            ),
          ),
          const Spacer(),
          const Padding(
            padding: EdgeInsets.only(bottom: 40.0),
            child: Text(
              'by赵星驰-20221060015-创新实验',
              style: TextStyle(
                fontSize: 18,
                color: Colors.black87,
              ),
            ),
          ),
        ],
      ),
      bottomNavigationBar: Container(
        color: Colors.white,
        height: 60,
        child: Row(
          mainAxisAlignment: MainAxisAlignment.center,
          children: const [
            Icon(Icons.home, color: Colors.green),
            SizedBox(width: 8),
            Text('首页', style: TextStyle(color: Colors.green, fontSize: 16)),
          ],
        ),
      ),
    );
  }
}

class BasicCalculationPage extends StatefulWidget {
  const BasicCalculationPage({Key? key}) : super(key: key);

  @override
  State<BasicCalculationPage> createState() => _BasicCalculationPageState();
}

class _BasicCalculationPageState extends State<BasicCalculationPage> {
  static const int totalQuestions = 5;
  late List<List<int>> questions;
  int currentIndex = 0;
  String userInput = '';
  int seconds = 0;
  late int answer;
  late String questionText;
  late Timer timer;

  @override
  void initState() {
    super.initState();
    questions = List.generate(totalQuestions, (_) {
      int a = 100 + (Random().nextInt(900));
      int b = 100 + (Random().nextInt(900));
      return [a, b];
    });
    _loadQuestion();
    _startTimer();
  }

  void _loadQuestion() {
    setState(() {
      userInput = '';
      seconds = 0;
      answer = questions[currentIndex][0] + questions[currentIndex][1];
      questionText = '${questions[currentIndex][0]}+${questions[currentIndex][1]}=';
    });
  }

  void _startTimer() {
    timer = Timer.periodic(const Duration(seconds: 1), (t) {
      setState(() {
        seconds++;
      });
    });
  }

  void _stopTimer() {
    timer.cancel();
  }

  void _nextQuestion() {
    if (currentIndex < totalQuestions - 1) {
      setState(() {
        currentIndex++;
      });
      _loadQuestion();
    } else {
      _stopTimer();
      showDialog(
        context: context,
        builder: (context) => AlertDialog(
          title: const Text('答题结束'),
          content: const Text('恭喜你完成所有题目！'),
          actions: [
            TextButton(
              onPressed: () {
                Navigator.of(context)
                  ..pop()
                  ..pop();
              },
              child: const Text('返回'),
            ),
          ],
        ),
      );
    }
  }

  void _onKeyTap(String value) {
    setState(() {
      if (value == '清空') {
        userInput = '';
      } else if (value == '退格') {
        if (userInput.isNotEmpty) {
          userInput = userInput.substring(0, userInput.length - 1);
        }
      } else if (value == '跳过') {
        _nextQuestion();
      } else if (value == '确认') {
        if (userInput.isNotEmpty && int.tryParse(userInput) == answer) {
          _nextQuestion();
        }
      } else {
        if (userInput.length < 6) {
          userInput += value;
        }
      }
    });
  }

  @override
  void dispose() {
    timer.cancel();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    final keys = [
      ['跳过', '清空', '退格'],
      ['1', '2', '3'],
      ['4', '5', '6'],
      ['7', '8', '9'],
      ['.', '0', '确认'],
    ];
    return Scaffold(
      backgroundColor: const Color(0xFFFFF3B0),
      appBar: AppBar(
        backgroundColor: const Color(0xFFFFE082),
        elevation: 0,
        titleSpacing: 0,
        title: Row(
          mainAxisAlignment: MainAxisAlignment.spaceBetween,
          children: [
            Padding(
              padding: const EdgeInsets.only(left: 8.0),
              child: Text('${currentIndex + 1}/$totalQuestions', style: const TextStyle(color: Colors.brown, fontSize: 20)),
            ),
            Padding(
              padding: const EdgeInsets.only(right: 16.0),
              child: Text('本题用时${seconds}秒', style: const TextStyle(color: Colors.brown, fontSize: 18)),
            ),
          ],
        ),
      ),
      body: Column(
        children: [
          const SizedBox(height: 40),
          Center(
            child: Text(
              questionText,
              style: const TextStyle(fontSize: 48, color: Colors.brown, fontWeight: FontWeight.w400),
            ),
          ),
          const SizedBox(height: 20),
          Center(
            child: Text(
              userInput,
              style: const TextStyle(fontSize: 36, color: Colors.black87),
            ),
          ),
          const Spacer(),
          Container(
            color: const Color(0xFFD9C97A),
            padding: const EdgeInsets.symmetric(vertical: 8, horizontal: 16),
            child: Column(
              children: keys.map((row) {
                return Row(
                  mainAxisAlignment: MainAxisAlignment.spaceEvenly,
                  children: row.map((key) {
                    return Padding(
                      padding: const EdgeInsets.all(6.0),
                      child: SizedBox(
                        width: 70,
                        height: 50,
                        child: ElevatedButton(
                          style: ElevatedButton.styleFrom(
                            backgroundColor: const Color(0xFFFFE082),
                            foregroundColor: Colors.brown,
                            shape: RoundedRectangleBorder(
                              borderRadius: BorderRadius.circular(8),
                            ),
                          ),
                          onPressed: () => _onKeyTap(key),
                          child: Text(
                            key,
                            style: const TextStyle(fontSize: 22, fontWeight: FontWeight.w400),
                          ),
                        ),
                      ),
                    );
                  }).toList(),
                );
              }).toList(),
            ),
          ),
        ],
      ),
    );
  }
}
